﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RestaurantApp.Web.Infrastructure.Binders
{
    public class TimeSpanBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)
        {
           ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            TimeSpan objectValue = new TimeSpan();

            var modelState = new System.Web.Mvc.ModelState { Value = valueResult };
            try
            {
                string[] parts = valueResult.AttemptedValue.Split(':'); //ex. 20:21
                if (parts.Length != 2) return null;
                int Hour = int.Parse(parts[0]);
                int Second = int.Parse(parts[1]);
                object actualValue = new TimeSpan(Hour, Second,0);
                bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
                objectValue = (TimeSpan)actualValue;
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            return objectValue;
        }
    }
}